import json
import time
# -- coding: UTF-8 --
from django.contrib.auth import authenticate, login, logout
from django.forms import Form
from django.shortcuts import render, redirect
from django.http import JsonResponse, HttpResponse

# Create your views here.
from django.views.decorators.csrf import csrf_exempt

from .ProcUnit import ProcUnit
from .forms import *


class Views(ProcUnit):
    def __init__(self):
        ProcUnit.__init__(self)

    # def Test(self,request,openid):
    #     return JsonResponse(self.getUserProjectDeviceByOpenid(openid))
    #
    # def Test2(self,request):
    #     return HttpResponse("tewrwe")
    #
    # def getDataAtoBView(self,request):
    #     if request.method == 'POST':
    #         form = getDataAtoBForm(request.POST)
    #         if form.is_valid():
    #             p=form.cleaned_data
    #             Dregister = Devices.objects.get(Dregister=form.cleaned_data["Dregister"])
    #             A=form.cleaned_data['A']
    #             B=form.cleaned_data['B']
    #             static,datas,datetime=self.getDataAtoBByDregister(Dregister=Dregister,A=A,B=B)
    #             return render(request,"ProjectData.html",{"data":datas,"static":static,"datetime":datetime})
    #
    #     #gui do
    #     if "gui" in request.GET:
    #         try:
    #             pid=request.GET["pid"]
    #         except:
    #             pid=0
    #         form=getDataAtoBForm()
    #         form.fields["Dregister"].widget=forms.widgets.Select(choices= Devices.objects.filter(Pid=pid).values_list("Dregister","Dregister") )
    #         return render(request, 'post.html', {"form":form})
    #     return self.Permissiondenied()

    def myloginView(self, request):
        # 只有当请求为 POST 时，才表示用户提交了注册信息
        if request.method == 'POST':
            form = LoginForm(request.POST)

            # 验证数据的合法性
            if form.is_valid():
                # 如果提交数据合法，调用表单的 save 方法将用户数据保存到数据库
                username = form.cleaned_data["username"]
                password = form.cleaned_data['password']
                ipAddr = self.get_client_ip(request=request)
                user = authenticate(username=username, password=password)
                if user is not None:
                    login(request, user)

                    # 跳转到成功页面
                    return JsonResponse(self.getOpenid(username=username, password=password, ipAddr=ipAddr))
                else:
                    return self.Permissiondenied()
            # 返回一个非法登录的错误页面
            # return JsonResponse(self.getOpenid(request=request,username=username,password=password,ipAddr=ipAddr))
            # user=
            # 注册成功，跳转回首页
            # return HttpResponse("%s%s"%(username,password))
        if "gui" in request.GET:
            # 请求不是 POST，表明用户正在访问注册页面，展示一个空的注册表单给用户
            form = LoginForm()

            # 渲染模板
            # 如果用户正在访问注册页面，则渲染的是一个空的注册表单
            # 如果用户通过表单提交注册信息，但是数据验证不合法，则渲染的是一个带有错误信息的表单
            return render(request, 'user/login.html', context={'form': form})
        return self.Permissiondenied()

    def mylogoutView(self, request):
        logout(request)
        return JsonResponse(self.retTag("logout", Type=True))

    def registerView(self, request):
        # 只有当请求为 POST 时，才表示用户提交了注册信息
        if request.method == 'POST':
            # request.POST 是一个类字典数据结构，记录了用户提交的注册信息
            # 这里提交的就是用户名（username）、密码（password）、邮箱（email）
            # 用这些数据实例化一个用户注册表单
            form = RegisterForm(request.POST)

            # 验证数据的合法性
            if form.is_valid():
                # 如果提交数据合法，调用表单的 save 方法将用户数据保存到数据库
                form.save()

                # 注册成功，跳转回首页
                return redirect('/')

        if "gui" in request.GET:
            form = RegisterForm()
            # 渲染模板
            # 如果用户正在访问注册页面，则渲染的是一个空的注册表单
            # 如果用户通过表单提交注册信息，但是数据验证不合法，则渲染的是一个带有错误信息的表单
            return render(request, 'user/register.html', context={'form': form})

        return self.Permissiondenied()

    def resetPasswordView(self, request):
        if request.GET("key", False) and request.GET("username", False):
            key = request.GET["key"]
            username = request.GET['username']
            if request.POST["new_password", False]:
                new_password = request.POST["new_password"]
                return JsonResponse(self.resetPasswordByKey(username=username, key=key, newPassword=new_password))
        if "gui" in request.GET:
            pass
        return self.Permissiondenied()

    def form_process_view(self, request):
        if request.method == 'POST':
            # 请求为 POST，利用用户提交的数据构造一个绑定了数据的表单
            form = Form(request.POST)

            if form.is_valid():
                # 表单数据合法
                # 进行其它处理...
                # 跳转
                return redirect('/')

        if "gui" in request.GET:
            form = Form()

            # 渲染模板
            # 如果不是 POST 请求，则渲染的是一个空的表单
            # 如果用户通过表单提交数据，但是数据验证不合法，则渲染的是一个带有错误信息的表单
            return render(request, 'template.html', context={'form': form})
        return self.Permissiondenied()

    # def creatProjectView(self,request):
    #     if request.method == 'GET':
    #         form = createProjectForm(request.GET)
    #         if form.is_valid():
    #             try:
    #                 title=form.cleaned_data["title"]
    #                 note=form.cleaned_data["note"]
    #                 description=form.cleaned_data["description"]
    #                 type=ProjectType.objects.get(PTid=form.cleaned_data['type'])
    #
    #                 uid=GeeJoansUser.objects.get(username=request.user)
    #                 # openid=UserLog.objects.filter(Uid=uid).order_by("-ULdatatime")[0].Uopenid
    #
    #
    #                 return JsonResponse(self.addProject(Uid=uid,Ptitle=title,Pnote=note,Pdescription=description,Ptype=type))
    #             except:
    #                 return self.Permissiondenied()
    #         form = createProjectForm()
    #         return render(request, 'get.html', {"form": form})
    #
    #     if "gui" in request.GET:
    #         form = createProjectForm()
    #         return render(request, 'get.html', {"form": form})
    #     return self.Permissiondenied()
    #
    # def delProjectView(self,request):
    #     try:
    #         uid = GeeJoansUser.objects.get(username=request.user).Uid
    #     except:
    #         uid = 0
    #     if request.method == 'GET':
    #         form = delProjectForm( request.GET)
    #         if form.is_valid():
    #             uid = GeeJoansUser.objects.get(username=request.user)
    #             pid=ProjectInformation.objects.get(Pid=form.cleaned_data["project"])
    #
    #             return JsonResponse(self.delProjectByPid(Pid=pid.Pid,Uid=uid))
    #         form.fields["project"].widget = forms.widgets.Select(
    #             choices=ProjectInformation.objects.filter(Uid=uid).values_list("Pid", "Ptitle"))
    #
    #         return render(request, 'get.html', {"form": form})
    #
    #     if "gui" in request.GET:
    #         form = delProjectForm()
    #         form.fields["project"].widget = forms.widgets.Select(
    #             choices=ProjectInformation.objects.filter(Uid=uid).values_list("Pid", "Ptitle"))
    #         return render(request, 'get.html', {"form": form})
    #     return self.Permissiondenied()
    #
    # def addDeviceView(self,request):
    #     try:
    #         uid = GeeJoansUser.objects.get(username=request.user).Uid
    #     except:
    #         uid = 0
    #
    #     form=addDeviceForm(request.GET)
    #     if form.is_valid():
    #         type=form.cleaned_data['Dtype']
    #         pid=ProjectInformation.objects.get(Pid=form.cleaned_data['pid'])
    #
    #         Ddata="web"
    #         return JsonResponse(self.addDevice(pid=pid,Dtype=type,Ddata=Ddata))
    #
    #
    #     # gui do
    #     if "gui" in request.GET:
    #         form.fields["pid"].widget = forms.widgets.Select(
    #             choices=ProjectInformation.objects.filter(Uid=uid).values_list("Pid", "Ptitle"))
    #         # form.fields["Dstatus"].initial=True
    #         return render(request, "get.html", {"form": form})
    #     return self.Permissiondenied()
    #
    # def delDeviceView(self,request):
    #     try:
    #         uid = GeeJoansUser.objects.get(username=request.user).Uid
    #     except:
    #         uid = 0
    #     if request.method=="POST":
    #         form=delDevicesForm(request.POST)
    #         if form.is_valid():
    #             if uid >=1:
    #                 Dregister=Devices.objects.get(Dregister=form.cleaned_data['device'])
    #                 Dregister.delete()
    #                 return JsonResponse(self.retTag("Device del OK",Type=True))
    #             else:
    #                 return self.Permissiondenied()
    #         else:
    #             return JsonResponse(self.retTag("don't have Devices"))
    #
    #     if "gui" in request.GET:
    #         form = delDevicesForm()
    #         form.fields["device"].widget = forms.widgets.Select(
    #             choices=Devices.objects.filter(Pid__Uid=uid).values_list("Dregister", "Dregister"))
    #         return render(request, "post.html", {"form": form})
    #
    #     return self.Permissiondenied()

    def ProjectManage(self, request, Type):
        """
        项目管理基本都是　get 方法
        所以　外围判断不需要

            四种类型分别处理不同的表格类型
        :param request:
        :param Type:
        :return:
        """
        form = ''
        # 用户信息获取 start
        try:
            uid = GeeJoansUser.objects.get(username=request.user)
        except:
            uid = 0
        # 　用户信息　end
        if Type == "add":
            form = createProjectForm(request.GET)
            if form.is_valid():
                try:
                    title = form.cleaned_data["title"]
                    note = form.cleaned_data["note"]
                    description = form.cleaned_data["description"]
                    type = ProjectType.objects.get(name=form.cleaned_data['type'])

                    return JsonResponse(
                        self.addProject(Uid=uid, Ptitle=title, Pnote=note, Pdescription=description, Ptype=type))
                except:
                    return self.Permissiondenied()

        if Type == 'del':
            form = delProjectForm(request.GET)
            if form.is_valid():
                pid = ProjectInformation.objects.get(Pid=form.cleaned_data["project"])

                return JsonResponse(self.delProjectByPid(Pid=pid.Pid, Uid=uid))
            form.fields["project"].widget = forms.widgets.Select(
                choices=ProjectInformation.objects.filter(Uid=uid).values_list("Pid", "Ptitle"))

        if Type == 'find':
            pis = ProjectInformation.objects.filter(Uid=uid).values("Ptitle", "Pdescription", "Pnote", "Ptype__name",
                                                                    "Pdatatime")
            return JsonResponse(self.retTag(list(pis), True))
            pass
        if Type == 'update':
            pass
        # 如有gui参数　则返回界面
        if 'gui' in request.GET:
            return render(request, 'get.html', {"form": form})

        return self.Permissiondenied()

    def DeviceManage(self, request, Type):
        form = ''
        # 用户信息获取 start
        try:
            uid = GeeJoansUser.objects.get(username=request.user)
        except:
            uid = 0
        if request.method == "POST":
            if Type == "add":

                form = addDeviceForm(request.POST)
                if form.is_valid() and uid is not 0:
                    type = form.cleaned_data['Dtype']
                    pid = ProjectInformation.objects.get(Pid=form.cleaned_data['pid'])

                    Ddata = "web"
                    return JsonResponse(self.addDevice(pid=pid, Dtype=type, Ddata=Ddata))

            if Type == "del" and uid is not 0:
                form = delDevicesForm(request.POST)
                if form.is_valid():
                    Dregister = Devices.objects.get(Dregister=form.cleaned_data['device'])
                    Dregister.delete()
                    return JsonResponse(self.retTag("Device del OK", Type=True))

            if Type == "find" and uid is not 0:
                # form = delDevicesForm(request.POST)
                # if form.is_valid():
                #     dev = Devices.objects.filter(Dregister=form.cleaned_data['device']).extra(select={"panid":"Dregister"})
                #     return JsonResponse(self.retTag(list(dev.values("panid","Pid_id","Dtype","Ddatetime","Dstatus")),Type=True))
                form = getDataAtoBForm(request.POST)
                if form.is_valid():
                    Dregister = Devices.objects.get(Dregister=form.cleaned_data["panid"])
                    f = form.cleaned_data['f']
                    t = form.cleaned_data['t']
                    static, datas, datetime = self.getDataAtoBByDregister(Dregister=Dregister, A=f, B=t)
                    if static == "success":
                        return render(request, "ProjectData.html",
                                      {"data": datas, "static": static, "datetime": datetime})
                    else:
                        return JsonResponse(self.retTag("emply"))

        # 如有gui参数　则返回界面
        if 'gui' in request.GET:
            if Type == "add":
                form = addDeviceForm()
                form.fields["pid"].widget = forms.Select(
                    choices=ProjectInformation.objects.filter(Uid=uid).values_list("Pid", "Ptitle"))

            if Type == "del":
                form = delDevicesForm()
                form.fields["device"].widget = forms.widgets.Select(
                    choices=Devices.objects.filter(Pid__Uid=uid).values_list("Dregister", "Dregister"))

            if Type == "find":
                form = getDataAtoBForm()
                form.fields["panid"].widget = forms.widgets.Select(
                    choices=Devices.objects.filter(Pid__Uid=uid).values_list("Dregister", "Dregister"))

            return render(request, 'post.html', {"form": form})

        return self.Permissiondenied()

    # @csrf_exempt
    def uploadDataView(self, request, panid):
        try:
            uid = GeeJoansUser.objects.get(username=request.user).Uid
        except:
            uid = 0
        if request.method == "POST":
            panid = str(panid)
            form = uploadDataForm(request.POST)
            if form.is_valid():
                data = form.cleaned_data['data']
                save = form.cleaned_data['save']

                if uid > 0 and save:
                    return JsonResponse(self.uploadData(panid=panid, data=data, save=True))
                else:
                    return JsonResponse(self.uploadData(panid=panid, data=data, save=False))

        if "gui" in request.GET:
            form = uploadDataForm()
            return render(request, "post.html", {"form": form})

        return self.Permissiondenied()

    def controlDataView(self, request, panid):
        try:
            uid = GeeJoansUser.objects.get(username=request.user).Uid
        except:
            uid = 0
        if request.method == "POST":
            form = controlDataForm(request.POST)
            if form.is_valid():
                panid = str(panid)
                data = form.cleaned_data["data"]
                if uid > 0:
                    return JsonResponse(self.doControl(panid=panid, data=data))
                else:
                    return JsonResponse(self.doControl(panid=panid, data=data))

        if "gui" in request.GET:
            form = controlDataForm()
            return render(request, "post.html", {"form": form})

        return self.Permissiondenied()

    def StatusView(self, request, panid):

        return JsonResponse(self.getMsgQueueInPanid(panid))

    def Permissiondenied(self):
        return JsonResponse(self.retTag("Permission denied"))
